package com.weido.nettyServer.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author rongdi
 * @date 2017年9月16日 下午3:36:08
 */
public class PropertyUtil {

    private static Properties props;

    synchronized static private void loadProps() {
        props = new Properties();
        InputStream in = null;
        
        try {
            try {
                String path = getJarDir()+"/application.properties";
                in = new FileInputStream(path);
            } catch(Exception e){
                in = PropertyUtil.class.getClassLoader().getResourceAsStream("application.properties");
            }
            props.load(in);
        } catch (FileNotFoundException e) {
            //logger.error("application.properties文件未找到");
        } catch (IOException e) {
            //logger.error("出现IOException");
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                //logger.error("application.properties文件流关闭出现异常");
            }
        }
    }

    public static String getProperty(String key) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }

    /**
     * 获取jar绝对路径
     * 
     * @return
     */
    public static String getJarPath() {
        File file = getFile();
        if (file == null)
            return null;
        return file.getAbsolutePath();
    }

    /**
     * 获取jar目录
     * 
     * @return
     */
    public static String getJarDir() {
        File file = getFile();
        if (file == null)
            return null;
        return getFile().getParent();
    }

    /**
     * 获取jar包名
     * 
     * @return
     */
    public static String getJarName() {
        File file = getFile();
        if (file == null)
            return null;
        return getFile().getName();
    }

    /**
     * 获取当前Jar文件
     * 
     * @return
     */
    private static File getFile() {
        // 关键是这行...
        String path = PropertyUtil.class.getProtectionDomain().getCodeSource()
                .getLocation().getFile();
        try {
            path = java.net.URLDecoder.decode(path, "UTF-8"); // 转换处理中文及空格
        } catch (java.io.UnsupportedEncodingException e) {
            return null;
        }
        return new File(path);
    }
}